import sys
import os
import logging

# 确保项目根目录在Python路径中
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from fastapi import FastAPI, status
from fastapi.responses import HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from app.routes.translate_route import router as translate_router
from app.routes.exchange_route import router as exchange_router
from app.routes.ip_location_route import router as ip_location_router
from app.routes.point_route import router as point_router
from app.routes.shopify_webhook_route import router as shopify_webhook_router
from app.routes.user_route import router as user_router
from app.routes.shopify_oauth_route import router as shopify_oauth_router
from app.routes.shopify_translate_route import router as shopify_translate_router
from app.routes.shopify_batch_translate_route import router as shopify_batch_translate_router
from app.routes.shopify_product_import_route import router as shopify_product_import_router
from app.routes.shopify_language_config_route import router as shopify_language_config_router
from app.routes.db_route import router as db_router
from app.routes.oauth_routes import router as oauth_call_back_router
from app.utils.error_handler import (
    not_found_handler,
    internal_error_handler,
    bad_gateway_handler,
    service_unavailable_handler
)
from app.conf.config import config, logger

import threading
from apscheduler.schedulers.blocking import BlockingScheduler
from app.services.rate_service import fetch_and_save_daily_rates
import os

# 全局调度器实例
scheduler = BlockingScheduler(timezone="Asia/Shanghai")  # 同步调度器


def run_scheduler():
    """运行同步调度器的线程函数"""
    try:
        logging.info(f"调度器线程启动（进程ID: {os.getpid()}）")
        scheduler.start()  # 阻塞运行，直到调度器停止
    except (KeyboardInterrupt, SystemExit):
        logging.info("调度器线程退出")


def start_scheduler_if_main_process():
    """仅在主进程启动调度器（避免多worker重复启动）"""
    # 获取当前进程ID
    current_pid = os.getpid()
    # 判断是否为主进程（uvicorn的主进程会启动worker子进程，仅主进程执行一次）
    if os.environ.get("UVICORN_WORKER_ID") is None:
        logging.info(f"主进程（PID: {current_pid}）启动调度器")

        # 添加定时任务：每分钟执行一次
        scheduler.add_job(
            fetch_and_save_daily_rates,
            "cron",
            hour=1,  # 凌晨1点
            minute=0,  # 0分（整点）
            second=0,  # 0秒（整分整秒）
            id="daily_rate_batch",
            replace_existing=True,
            misfire_grace_time=30
        )

        # 启动调度器线程（与uvicorn服务并行）
        scheduler_thread = threading.Thread(
            target=run_scheduler,
            name="SchedulerThread",
            daemon=True  # 主线程退出时，调度器线程自动退出
        )
        scheduler_thread.start()
    else:
        logging.info(f"工作进程（PID: {current_pid}）不启动调度器")

def create_app() -> FastAPI:
    logger.debug("开始创建FastAPI应用实例")
    
    # 配置API文档，尝试解决CDN加载问题
    app = FastAPI(
        title="Translation & Exchange API",
        description="FastAPI service with Translation and Currency Exchange functions",
        version="1.0.0",
        debug=config.DEBUG,
        # 启用API文档
        docs_url="/docs",
        redoc_url="/redoc",
        # 尝试通过配置减少对外部CDN的依赖
        openapi_url="/openapi.json"  # 确保OpenAPI规范可访问
    )
    
    # 配置CORS中间件
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],  # 在生产环境中应该限制为特定域名
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    
    logger.debug("FastAPI应用实例创建完成")

    # 注册路由
    logger.debug("开始注册路由")
    app.include_router(translate_router)
    logger.debug("translate_router已注册")
    app.include_router(exchange_router)
    logger.debug("exchange_router已注册")
    app.include_router(ip_location_router)
    logger.debug("ip_location_router已注册")
    app.include_router(point_router)
    logger.debug("point_router已注册")
    app.include_router(shopify_webhook_router)
    logger.debug("shopify_webhook_router已注册")
    app.include_router(user_router)
    logger.debug("user_router已注册")
    app.include_router(shopify_oauth_router)
    logger.debug("shopify_oauth_router已注册")
    app.include_router(shopify_translate_router)
    logger.debug("shopify_translate_router已注册")
    app.include_router(shopify_batch_translate_router)
    logger.debug("shopify_batch_translate_router已注册")
    app.include_router(shopify_product_import_router)
    logger.debug("shopify_product_import_router已注册")
    app.include_router(shopify_language_config_router)
    logger.debug("shopify_language_config_router已注册")
    app.include_router(db_router)
    logger.debug("db_router已注册")
    app.include_router(oauth_call_back_router)
    logger.debug("oauth_call_back_router已注册")
    logger.debug("所有路由注册完成")

    # 根路径
    @app.get("/", tags=["root"])
    async def root():
        return {
            "message": "Translation & Currency Exchange API is running",  # 更新消息
            "status": "ok",
            "available_endpoints": {
                "translation": "/api/v1/translate",
                "exchange_rate": "/api/v1/exchange/rate",
                "exchange_calculate": "/api/v1/exchange/calculate",
                "ip_location": "/api/v1/ip-location",
                "points_balance": "/api/v1/points/balance",
                "points_recharge": "/api/v1/points/recharge",
                "points_history": "/api/v1/points/history",
                "shopify_webhooks": "/api/v1/webhooks/shopify/...",
                "shopify_oauth": "/api/v1/oauth/shopify/callback",
                "shopify_translate": "/api/v1/shopify/translate-product",
                "shopify_collect": "/api/v1/shopify/collect-products",
                "shopify_translate_all": "/api/v1/shopify/translate-all-products",
                "batch_translate_all": "/api/v1/batch-translate-all-products",
                "shopify_import_products": "/api/v1/shopify/import-products",
                "shopify_import_variants": "/api/v1/shopify/import-product-variants",
                "shopify_language_config": "/api/v1/shopify/language/config",
                "shopify_language_publish": "/api/v1/shopify/language/publish"
            }
        }

    # 注册错误处理器（保持原有配置）
    app.add_exception_handler(
        status.HTTP_404_NOT_FOUND,
        not_found_handler
    )
    app.add_exception_handler(
        status.HTTP_500_INTERNAL_SERVER_ERROR,
        internal_error_handler
    )
    app.add_exception_handler(
        status.HTTP_502_BAD_GATEWAY,
        bad_gateway_handler
    )
    app.add_exception_handler(
        status.HTTP_503_SERVICE_UNAVAILABLE,
        service_unavailable_handler
    )

    # 添加一个简单的自定义API文档端点，不依赖外部CDN
    @app.get("/api-docs")
    async def custom_api_docs():
        return {
            "api_name": "Translation & Exchange API",
            "version": "1.0.0",
            "endpoints": [
                "/translate",
                "/exchange-rate",
                "/ip-info",
                "/points",
                # 列出主要端点
            ],
            "docs": "请访问 /openapi.json 获取完整的API规范"
        }
        
    # 添加HTML版本的简单文档页面
    @app.get("/simple-docs", response_class=HTMLResponse)
    async def simple_html_docs():
        return """
        <!DOCTYPE html>
        <html>
        <head>
            <title>API Documentation</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; }
                h1 { color: #333; }
                ul { list-style-type: none; padding: 0; }
                li { margin: 10px 0; padding: 10px; border: 1px solid #ddd; }
            </style>
        </head>
        <body>
            <h1>Translation & Exchange API</h1>
            <p>Version: 1.0.0</p>
            <h2>Available Endpoints:</h2>
            <ul>
                <li><strong>POST /translate</strong> - Translate text between languages</li>
                <li><strong>GET /exchange-rate</strong> - Get currency exchange rates</li>
                <li><strong>GET /ip-info</strong> - Get IP location information</li>
                <li><strong>GET /points</strong> - Get points information</li>
                <li><strong>GET /openapi.json</strong> - Get complete OpenAPI specification</li>
            </ul>
        </body>
        </html>
        """
    
    return app


app = create_app()

# 确保全局日志级别设置为DEBUG
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)

if __name__ == "__main__":
    import uvicorn
    import sys

    import uvicorn
    import sys

    logger = logging.getLogger(__name__)
    logger.debug(f"Python版本: {sys.version}")
    logger.debug("开始启动应用")
    try:
        start_scheduler_if_main_process()  # 定时器
        SSL_CERT_PATH = 'server.crt'  # 证书文件路径
        SSL_KEY_PATH = 'server.key'  # 私钥文件路径
        logger.debug("调度器启动完成")

        logger.debug("开始启动uvicorn服务器")
        uvicorn.run(
            "app.main:app",
            host="0.0.0.0",
            port=5001,
            reload=False,
            workers=1,
            ssl_keyfile=SSL_KEY_PATH,  # 私钥路径
            ssl_certfile=SSL_CERT_PATH
            #    log_level="debug"  # 启用详细日志
        )
    except Exception as e:
        logger.error(f"应用启动失败: {e}", exc_info=True)

